<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('鉴定报告列表')"/>
</head>
<body class="gray-bg">
<div class="container-div">
    <div class="row">
        <div class="col-sm-12 search-collapse">
            <form id="formId">
                <div class="select-list">
                    <ul>
                        <li>
                            <label>送鉴单位：</label>
                            <input type="text" name="params[sendUnit]"/>
                        </li>
                        <li>
                            <label>来文文号：</label>
                            <input type="text" name="params[documentNum]"/>
                        </li>
                        <li class="select-time">
                            <label>受理时间：</label>
                            <input type="text" class="time-input" id="startTime" placeholder="开始时间"
                                   name="params[startTime]"/>
                            <span>-</span>
                            <input type="text" class="time-input" id="endTime" placeholder="结束时间"
                                   name="params[endTime]"/>
                        </li>
                        <li>
                            <label>鉴定结论：</label>
                            <select name="appraCon" th:with="type=${@dict.getType('id_report_conclusion')}">
                                <option value="">--所有--</option>
                                <option th:each="dict : ${type}" th:text="${dict.dictLabel}"
                                        th:value="${dict.dictValue}"></option>
                            </select>

                        </li>
                        <li>
                            <label>是否启用：</label>
                            <select name="params[isUse]">
                                <option value="">--所有--</option>
                                <option value="启用">启用</option>
                                <option value="关闭">关闭</option>

                            </select>
                        </li>
                        <li>
                            <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i
                                    class="fa fa-search"></i>&nbsp;搜索</a>
                            <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i
                                    class="fa fa-refresh"></i>&nbsp;重置</a>
                        </li>
                    </ul>
                </div>
            </form>
        </div>

        <div class="btn-group-sm" id="toolbar" role="group">
            <a class="btn btn-success" onclick="$.operate.addTab()" shiro:hasPermission="publish:IdReport:add">
                <i class="fa fa-plus"></i> 添加
            </a>
            <!--<a class="btn btn-primary single disabled" onclick="$.operate.editTab()"-->
               <!--shiro:hasPermission="publish:IdReport:edit">-->
                <!--<i class="fa fa-edit"></i> 修改-->
            <!--</a>-->
            <!--    <a class="btn btn-danger multiple disabled" onclick="$.operate.removeAll()" shiro:hasPermission="publish:IdReport:remove">
                    <i class="fa fa-remove"></i> 删除
                </a>-->
            <a class="btn btn-info" onclick="$.table.importExcel()" shiro:hasPermission="publish:IdReport:import">
                <i class="fa fa-upload"></i> 导入
            </a>
            <a class="btn btn-warning" onclick="$.table.exportExcelRecord('formId')" shiro:hasPermission="publish:IdReport:export">
                <i class="fa fa-download"></i> 导出
            </a>
        </div>
        <div class="col-sm-12 select-table table-striped">
            <table id="bootstrap-table"></table>
        </div>
    </div>
</div>
<th:block th:include="include :: footer"/>
<script th:inline="javascript">
    var editFlag = [[${@permission.hasPermi('publish:IdReport:edit')}]];
    var examineFlag = [[${@permission.hasPermi('publish:IdReport:examine')}]];

    var sessionScope = [[${session}]];
    var removeFlag = "";
    var prefix = ctx + "publish/report";
    var reportFormData = {};

    var userList=[];
    $.ajax({
        type: "post",
        url: ctx + "system/user/list",
        data: [pageSize=100,pageNum=1],
        cache: false,
        contentType: false,
        processData: false,
        dataType: 'json',
        async:false,
        success: function (result) {
            if (result.code == web_status.SUCCESS) {
                // console.log(result.rows)
                userList=result.rows;

            } else {
                $.modal.alertError(result.msg);
            }
        },
        error: function (error) {
            // $.modal.alertWarning("jia。");
        }
    });


    $(function () {



        var options = {
            url: prefix + "/list",
            createUrl: prefix + "/add",
            updateUrl: prefix + "/edit/{id}",
            removeUrl: prefix + "/remove",
            exportUrl: prefix + "/export",
            reportUrl: "/sys/word/report/",
            reportIssueUrl: "/sys/word/issue/",
            detailUrl: prefix + "/detail/{id}",
            assistUrl: "/sys/word/assist/",
            approvalhistoryUrl: "/publish/record/detail/{id},1",
            importTemplateUrl: prefix + "/importTemplate",
            importUrl: prefix + "/importData",
            refreshUrl: "/publish/report/refresh/{id}", //一键更新

            sortName: "createTime",
            sortOrder: "desc",
            modalName: "鉴定报告",
            columns: [{
                checkbox: true
            },
                {
                    field: 'id',
                    title: '编号',
                    visible: false
                },
                // {
                //     field: 'index',
                //     align: 'center',
                //     title: "序号",
                //     formatter: function (value, row, index) {
                //         var columnIndex = $.common.sprintf("<input type='hidden' name='index' value='%s'>", $.table.serialNumber(index));
                //         return columnIndex + $.table.serialNumber(index);
                //     }
                // },

                {
                    field: 'idAcceptRegister.sendUnit',
                    title: '送鉴单位',
                    sortable: true,
                },
                {
                    field: 'idAcceptRegister.documentNum',
                    title: '来文文号',
                    sortable: true,
                },
                {
                    field: 'sampleNumber',
                    title: '样本数量',
                    sortable: true,
                },
                {
                    field: 'takeover',
                    title: '创建人',
                    sortable: true,
                },
                {
                    field: 'pushUser',
                    title: '提交人',
                    formatter: function (value, row, index) {
                        console.log("userList"+userList.length)
                        var str='-';
                        $.each(userList,function (n,values) {
                            // console.log(values)
                            // console.log(values.userId==value)
                            // console.log(values.userId+"---"+value+"---"+values.userName)

                            if(values.userId==value){
                                str=values.userName;
                                return false;
                            }
                        })

                        return str;
                    },
                    sortable: true,
                },
                {
                    field: 'acceptTime',
                    title: '案件受理时间',
                    sortable: true,
                },
                {
                    field: 'appraCon',
                    title: '鉴定结论',
                    sortable: true,
                },
                {
                    field: 'status',
                    title: '状态',
                    formatter: function (value, row, index) {
                        var text = "";
                        value = Number(value);
                        switch (value) {
                            case 1:
                                text = "草稿";
                                break;
                            case 2:
                                text = "待初审";
                                break;
                            case 3:
                                text = "待复审";
                                break;
                            case 4:
                                text = "待终审";
                                break;
                            case 5:
                                text = "初审驳回";
                                break;
                            case 6:
                                text = "复审驳回";
                                break;
                            case 7:
                                text = "终审驳回";
                                break;
                            case 8:
                                text = "初审通过";
                                break;
                            case 9:
                                text = "复审通过";
                                break;
                            case 10:
                                text = "终审通过";
                                break;
                        }
                        return text;
                    },
                    sortable: true,

                },
                {
                    field: 'isUse',
                    title: '是否启用',
                    formatter: function (value, row, index) {
                        return statusTools(row);
                    }
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function (value, row, index) {
                        var actions = [], flag = false, canEdit = false;
                        var userId = sessionScope["org.apache.shiro.subject.support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY"].primaryPrincipal.userId;
                        var userIds = row.auditorId;
                        if ($.common.isEmpty(row.auditorId)) {
                            userIds = 0;
                        }else{
                            // 截取第一个审批人
                            userIds=userIds.split(",")[0];
                        }
                        // 是否是指定审批用户
                        if (filter(row.auditorId, userId)) {
                            flag = true;
                        }
                        // 是否已审批
                        if (filter(row.appRemark, userId)) {
                            flag = false;
                        }
                        var statusCode = Number(row.status);
                        // 状态是否已经为退回
                        if (statusCode == 1) {
                            flag = false;
                        }
                        var auditorPass = Number(row.auditor);//审核人员
                        var level = Number(row.approvalLevel);//审核进行环节
                        // 送初审,创建用户为初审用户
                        if (statusCode == 1 ||statusCode == 2|| (statusCode == 5 && (level == 0 || level == 1))) {
                            if (filter(row.createBy, userId)) {
                                canEdit = true;
                                if (statusCode != 2) {
                                    actions.push('<a style="margin-right: 3px" class="btn btn-warning btn-xs" href="javascript:void(0)" onclick="openWinUser(\'' + row.id + '\',\'' + row.approvalLevel + '\',\'' + userIds + '\')"><i class="fa fa-check"></i>送初审</a>');
                                }else{//提交审核之后只能审核人才能修改编辑
                                    canEdit = false;
                                }
                            }
                            // 送复审
                        } else if (statusCode == 6||statusCode == 8 || statusCode == 3 && level == 2) {
                            // 驳回
                            if ((statusCode == 6||statusCode == 8) && filter(row.auditorId, userId)) {
                                canEdit = true;
                                actions.push('<a style="margin-right: 3px" class="btn btn-warning btn-xs" href="javascript:void(0)" onclick="openWinUser(\'' + row.id + '\',\'' + row.approvalLevel + '\',\'' + userIds + '\')"><i class="fa fa-check"></i>送复审</a>');
                            } else if (auditorPass == 1 && filter(row.auditorId, userId)) {
                                // 通过
                                canEdit = true;
                                actions.push('<a style="margin-right: 3px" class="btn btn-warning btn-xs" href="javascript:void(0)" onclick="openWinUser(\'' + row.id + '\',\'' + row.approvalLevel + '\',\'' + userIds + '\')"><i class="fa fa-check"></i>送复审</a>');
                            } else if (auditorPass == 0 && stringEqual(row.pushUser, userId))
                            {
                                // 送审人编辑
                                canEdit = false;
                            }
                            // 送终审
                        } else if (statusCode == 7 ||statusCode == 9 || statusCode == 4 && level == 3) {
                            // 驳回
                            if ((statusCode == 7||statusCode == 9) && filter(row.auditorId, userId)) {
                                canEdit = true;
                                actions.push('<a style="margin-right: 3px" class="btn btn-warning btn-xs" href="javascript:void(0)" onclick="openWinUser(\'' + row.id + '\',\'' + row.approvalLevel + '\',\'' + userIds + '\')"><i class="fa fa-check"></i>送终审</a>');
                            } else if (auditorPass == 1 && filter(row.auditorId, userId)) {
                                // 通过
                                canEdit = true;
                                actions.push('<a style="margin-right: 3px" class="btn btn-warning btn-xs" href="javascript:void(0)" onclick="openWinUser(\'' + row.id + '\',\'' + row.approvalLevel + '\',\'' + userIds + '\')"><i class="fa fa-check"></i>送终审</a>');
                            } else if (auditorPass == 0 && stringEqual(row.pushUser, userId)) {
                                // 通过
                                canEdit = true;
                            }
                        }

                        // 具有审批权限
                        if (flag) {
                            canEdit = true;
                            actions.push('<a style="margin-right: 3px" class="btn btn-warning btn-xs " href="javascript:void(0)" onclick="audit(\'' + row.id + '\',\'' + row.approvalLevel + '\')"><i class="fa fa-check"></i>审核</a>');
                        }
                        // 具有编辑权限
                        if (canEdit) {
                            actions.push('<a class="btn btn-success btn-xs " href="javascript:void(0)" onclick="$.operate.editTab(\'' + row.id + '\')"><i class="fa fa-edit"></i>编辑</a> ');
                        }

                        var more = [];
                        more.push("<a class='btn btn-default btn-xs' href='javascript:void(0)' onclick='windOpensTwo(" + "1," + row.id + ","+row.registerId+","+row.sampleIds+")'><i class='glyphicon  glyphicon-open'></i>鉴定结论</a>");
                        more.push("<a class='btn btn-default btn-xs' href='javascript:void(0)' onclick='windOpensTwo(" + "2," + row.id + ","+row.registerId+","+row.sampleIds+")'><i class='fa fa-check-square-o'></i>签发单</a>");
                        // more.push("<a class='btn btn-default btn-xs' href='javascript:void(0)' onclick='windOpensTwo(" + "3," + row.id + ","+row.registerId+","+row.sampleIds+")'><i class='fa fa-refresh'></i>一键更新</a>");


                        actions.push('<a style="margin-right: 3px" tabindex="0" class="btn btn-info btn-xs" role="button" data-container="body" data-placement="left" data-toggle="popover" data-html="true" data-trigger="hover" data-content="' + more.join('') + '"><i class="fa fa-chevron-circle-right"></i>更多操作</a>');


                        // actions.push('<a class="btn btn-info btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="window.open(\'' + table.options.reportUrl + row.id + '\');"><i class="glyphicon  glyphicon-open"></i>鉴定报告</a> ');
                        // actions.push('<a class="btn btn-info btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="window.open(\'' + table.options.reportIssueUrl + row.id + '\');"><i class="glyphicon  glyphicon-open"></i>签发单</a> ');

                        // actions.push('<a class="btn btn-info btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="window.open(\'' + table.options.reportUrl + row.id + '\');"><i class="glyphicon  glyphicon-open"></i>鉴定报告</a> ');
                        // actions.push('<a class="btn btn-info btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="window.open(\'' + table.options.reportIssueUrl + row.id + '\');"><i class="glyphicon  glyphicon-open"></i>签发单</a> ');
                        actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="$.operate.detailTab(\'' + row.id + '\')"><i class="fa fa-book"></i>查看</a> ');
                        // if(row.appraCon=="正式出版物"){
                        //     actions.push("<a class='btn btn-default btn-xs " + editFlag + "' href='javascript:void(0)' onclick='windOpens(" + "4,"+row.id +","+(row.remark!=null?1:row.remark)+")'><i class='fa fa-check-square-o'></i>协查函</a>");
                        // }
                        // actions.push('<a class="btn btn-danger btn-xs ' + removeFlag + '" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.id + '\')"><i class="fa fa-remove"></i>删除</a>');
                        if (statusCode != 1) {
                            actions.push('<a class="btn btn-warning btn-xs " href="javascript:void(0)" onclick="$.operate.openParamWindow(\'审批历史\',\'approvalhistoryUrl\',\'' + row.id + '\')"><i class="fa fa-check"></i>审核记录</a>');
                        }
                        return actions.join('');
                    }
                }]
        };
        $.table.init(options);
    });

    function windOpensTwo(num, id, registerId,sampleIds) {
        debugger
        if($.common.isEmpty(registerId)||$.common.isEmpty(sampleIds)){
            layer.alert("请确认关联案件和关联样本已选择",{icon:8})
            return;
        }
        if (num == 1) {//鉴定结论
            window.open(table.options.reportUrl + id)

        } else if (num == 2) {//签发单
            window.open(table.options.reportIssueUrl + id)

        } else if (num == 3) {
            table.set();
            $.modal.confirm("确定要更新该条记录所有的文档吗？", function () {
                var url = $.common.isEmpty(id) ? table.options.refreshUrl : table.options.refreshUrl.replace("{id}", id);
                if (table.options.type == table_type.bootstrapTreeTable) {
                    $.operate.get(url);
                } else {
                    var data = {"id": id};
                    $.operate.submit(url, "post", "json", data);
                }
            });
        }
    }

    function openWinUser(id, level,userId) {
        // 数据id
        reportFormData.taskRecordId = id;
        reportFormData.taskApprovalLevel = level;
        $.modal.open("选择审核人员", "/system/user/userSelectPage/"+userId);
    }

    // 增加审批人的选择
    function setUser(rows) {
        var userId = "", userName = "";
        if (rows != null && rows.length > 0) {
            for (var i = 0, end = rows.length; i < end; i++) {
                userId += rows[i].userId + ",";
                if (i == (end - 1)) {
                    userName += rows[i].userName;
                } else {
                    userName += rows[i].userName + ",";
                }
            }
            reportFormData.taskUserIds = userId;
            reportFormData.auditor = userName;
            submitSelect();
        }

        // 提交选择人信息
        function submitSelect() {
            $.ajax('/publish/approval/addOrUpdateTask', {
                type: "post",
                timeout: 30000,
                data: reportFormData,
                success: function (res) {
                    if (res.code == 0) {
                        layer.alert("添加送审成功!");
                        addApprovalUser();
                    }
                },
                error: function (res) {
                    console.log(res);
                }
            });
        }

        // 添加送审人员信息
        function addApprovalUser() {
            var formUserData = {};
            formUserData.recordId = reportFormData.taskRecordId;
            formUserData.systemModule = 1;
            formUserData.approvalReason = reportFormData.taskUserIds + "|" + reportFormData.auditor;
            // 送审人员
            formUserData.approvalType = 1;
            formUserData.approvalStatus = 1;
            // 送审消息
            if (reportFormData.taskApprovalLevel == 1) {
                formUserData.approvalTitle = "送初审";
            } else if (reportFormData.taskApprovalLevel == 2) {
                formUserData.approvalTitle = "送复审";
            } else if (reportFormData.taskApprovalLevel == 3) {
                formUserData.approvalTitle = "送终审";
            }

            $.ajax('/publish/record/addApprovalUser', {
                type: "post",
                timeout: 3000,
                data: formUserData,
                success: function (res) {
                    if (res.code == 0) {
                        $.table.refresh();
                    }
                },
                error: function (res) {
                    console.log(res);
                }
            });
        }
    }

    function stringEqual(paramsUser, user) {
        var result = false;
        if ($.common.isNotEmpty(paramsUser) && $.common.isNotEmpty(user)) {
            if (Number(paramsUser) == Number(user)) {
                result = true;
            }
        }
        return result;
    }

    function filter(params, id) {
        var resultOk = false;
        if ($.common.isNotEmpty(params)) {
            var arrayList = params.split(",");
            for (var i = 0, end = arrayList.length; i < end; i++) {
                if (arrayList[i] != "" && arrayList[i] == id) {
                    resultOk = true;
                    break;
                }
            }
        }
        return resultOk;
    }

    /* 审核 */
    function audit(id, level) {
        var options = {
            title: '鉴定报告审核',
            width: "550",
            height: "350",
            url: ctx + "publish/report/openApprovalWindow",
            height: "300",
            url: ctx + "publish/report/audit",
            callBack: function (index, layero) {
                var body = layer.getChildFrame('body', index);
                /*审核状态 1:未通过 3:待审核 5:通过*/
                var status = body.find('input[name="auditStatus"]:checked').val();
                var remark = body.find('[name="remark"]').val();
                var formData = {
                    "taskRecordId": id,
                    "taskStatus": status,
                    "approvalReason": remark,
                    "taskApprovalLevel": level,
                }
                $.operate.post(window.location.origin + "/publish/approval/handleTaskApproval", formData,function(){
                    setTimeout(function () {
                        //通过审核按钮控制样本状态再控制案件状态
                        window.top.$('.RuoYi_iframe[data-id^="/publish/identsample/listByRegister?registerId"]').each(function(){
                            this.contentWindow.location.reload();
                        })
                    }, 500);
                });
                layer.close(index);
            }
        };
        $.modal.openOptions(options);
    }

    function windOpens(num, id, wordid) {
        console.log(num)
        if (num == 1) {
            window.open(table.options.acceptUrl + id)

        } else if (num == 2) {
            window.open(table.options.registerUrl + id)

        } else if (num == 3) {
            window.open(table.options.acceptUrl + id)

        } else if (num == 4) {
            //为空提醒选择
            if ($.common.isEmpty(wordid)) {
                assisAlter(id)
            } else {
                window.open(table.options.assistUrl + id)
            }
        }
    }

    // 导入数据
    function assisAlter(id) {
        table.set();
        var currentId = 'assitCheck';
        layer.open({
            type: 1,
            area: ['300px', '200px'],
            fix: false,
            //不固定
            maxmin: true,
            shade: 0.3,
            title: '协查函类型选择',
            content: $('#' + currentId).html(),
            btn: ['<i class="fa fa-check"></i> 确认', '<i class="fa fa-remove"></i> 取消'],
            // 弹层外区域关闭
            shadeClose: true,
            btn1: function (index, layero) {
                var file = layero.find('input[name="yesNo"]:checked').val();
                console.log(file)
                $.modal.closeAll();
                $.table.refresh();
                window.open(table.options.assistUrl + id + "?yesNo=" + file)
            }
        });
    }

    /* 用户状态显示 */
    function statusTools(row) {
        if (row.isUse == '0') {
            return '<i class=\"fa fa-toggle-off text-info fa-2x\" onclick="enable(\'' + row.id + '\')"></i> ';
        } else {
            return '<i class=\"fa fa-toggle-on text-info fa-2x\" onclick="disable(\'' + row.id + '\')"></i> ';
        }
    }

    /* 是否启用-开启 */
    function enable(id) {
        $.modal.confirm("确认要开启吗？", function () {
            $.operate.post(prefix + "/changeStatus", {"id": id, "isUse": '1'});
        })
    }

    /* 是否启用-关闭 */
    function disable(id) {
        $.modal.confirm("确认要关闭吗？", function () {
            $.operate.post(prefix + "/changeStatus", {"id": id, "isUse": '0'});
        })
    }

    function importTemplateReport() {
        window.location.href = prefix + "/doLoad";
    }

    //下载正式出版物模板
    function importReportTemplate() {
        window.location.href = prefix + "/doLoad";
    }
</script>
<!-- 导入区域 -->
<script id="importTpl" type="text/template">
    <form enctype="multipart/form-data" class="mt20 mb10">
        <div class="col-xs-offset-1">
            <input type="file" id="file" name="file"/>
            <div class="mt10 pt5">
                <!--                <input type="checkbox" id="updateSupport" name="updateSupport" title="如果登录账户已经存在，更新这条数据。"> 是否更新已经存在的用户数据-->
                &nbsp; <a href="/excelTemplate/report/正式、其他出版物模板.xlsx" class="btn btn-default btn-xs"><i
                    class="fa fa-file-excel-o"></i> 下载正式、其他出版物模板</a>
                &nbsp; <a href="/excelTemplate/report/非法出版物模板.xlsx"  class="btn btn-default btn-xs"><i
                    class="fa fa-file-excel-o"></i> 下载非法出版物模板</a>
            </div>
            <font color="red" class="pull-left mt10">
                提示：仅允许导入“xls”或“xlsx”格式文件！
            </font>
        </div>
    </form>
</script>
<!-- 送达单 -->
<script id="assitCheck" type="text/template">
    <form enctype="multipart/form-data" class="mt20 mb10">
        <div class="col-xs-offset-1">
            <div class="mt10 pt5">
                <input type="radio" value="no" name="yesNo" title="无附件" checked> 无附件
                <input type="radio" value="yes" name="yesNo" title="有附件"> 有附件

            </div>

        </div>
    </form>
</script>
</body>
</html>
